package com.dz.scrm.mvp.ui.fragment

import android.annotation.SuppressLint
import android.graphics.Typeface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.dz.scrm.R
import com.dz.scrm.constant.INTENT_PHONE_RECORD
import com.dz.scrm.mvp.model.entity.*
import com.dz.scrm.mvp.presenter.DZPresent
import com.dz.scrm.mvp.ui.PhoneDetailActivity
import com.dz.scrm.utils.*
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.tbruyelle.rxpermissions2.RxPermissions
import com.zackratos.ultimatebarx.ultimatebarx.addStatusBarTopPadding
import kotlinx.android.synthetic.main.fragment_phone_record.*
import me.jessyan.art.base.BaseFragment
import me.jessyan.art.mvp.IView
import me.jessyan.art.mvp.Message
import me.jessyan.art.utils.ArtUtils
import org.litepal.LitePal
import org.litepal.extension.find


/**
 * 作者：fanda
 * 日期：2021/4/23 11:51
 * 描述：通话记录
 */
class PhoneRecordFragment : BaseFragment<DZPresent>(), IView {
    private val mTitles = listOf("全部通话", "未接来电")
    private val mTabEntities = ArrayList<CustomTabEntity>()
    private lateinit var headerView: View
    private lateinit var mAllCallAdapter: AllCallAdapter
    private lateinit var mWaitCallAdapter: WaitCallAdapter
    private val companyInfoBean by lazy {
        getInfoBean<CompanyInfoBean>(SharedPreferencesUtil.COMPANY_INFO)
    }

    companion object {
        @JvmStatic
        fun getInstance(): PhoneRecordFragment {
            return PhoneRecordFragment().apply {
            }
        }
    }

    override fun initView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return inflater.inflate(R.layout.fragment_phone_record, container, false)
    }

    @SuppressLint("InflateParams", "CheckResult")
    override fun initData(savedInstanceState: Bundle?) {
        tv_title.addStatusBarTopPadding()
        tv_title.typeface = Typeface.defaultFromStyle(Typeface.BOLD)//加粗
        initTabLayout()
        initRecyclerView()
        initListeners()
    }

    private fun initRecyclerView() {
        mAllCallAdapter = AllCallAdapter(isHiddenPhoneNum())
        mWaitCallAdapter = WaitCallAdapter(isHiddenPhoneNum())
        mAllCallAdapter.setEmptyView(layoutInflater.inflate(R.layout.layout_empty, null))

        all_call_recyclerView.adapter = mAllCallAdapter
        all_call_recyclerView.layoutManager = LinearLayoutManager(mContext)

        mWaitCallAdapter.setEmptyView(layoutInflater.inflate(R.layout.layout_empty, null))
        wait_call_recyclerView.adapter = mWaitCallAdapter
        wait_call_recyclerView.layoutManager = LinearLayoutManager(mContext)
        loadRecordData()
    }

    fun loadRecordData() {
        val cacheAllPhoneRecordList = LitePal.order("phoneStartTime").where("user_id = ? and tenant_id = ?", companyInfoBean?.user_id, companyInfoBean?.tenant_id).find<CacheAllPhoneRecord>().reversed()
        mAllCallAdapter.setNewInstance(cacheAllPhoneRecordList.toMutableList())
        val cacheWaitPhoneRecordList = LitePal.order("phoneStartTime").where("user_id = ? and tenant_id = ?", companyInfoBean?.user_id, companyInfoBean?.tenant_id).find<CacheWaitPhoneRecord>().reversed()
        mWaitCallAdapter.setNewInstance(cacheWaitPhoneRecordList.toMutableList())

        cacheAllPhoneRecordList.forEach { LoggerUtils.d(it.phoneStartTime.toString()) }
        cacheWaitPhoneRecordList.forEach { LoggerUtils.d(it.phoneStartTime.toString()) }

    }

    private fun initListeners() {
        mAllCallAdapter.setOnItemClickListener { _, _, position ->
            activity?.callPhone(mAllCallAdapter.getItem(position).customerPhone)
        }
        mAllCallAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.iv_phone_tips -> {
                    launchActivity<PhoneDetailActivity>(mContext) {
                        putExtra(INTENT_PHONE_RECORD, adapter.getItem(position) as CachePhoneRecord)
                    }
                }
            }
        }
        mWaitCallAdapter.setOnItemClickListener { _, _, position ->
            activity?.callPhone(mAllCallAdapter.getItem(position).customerPhone)
        }
        mWaitCallAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.iv_phone_tips -> {
                    launchActivity<PhoneDetailActivity>(mContext) {
                        putExtra(INTENT_PHONE_RECORD, adapter.getItem(position) as CachePhoneRecord)
                    }
                }
            }
        }
    }

    private fun initTabLayout() {
        headerView = layoutInflater.inflate(R.layout.header_phone_record, null)
        for ((index, title) in mTitles.withIndex()) {
            mTabEntities.add(index, TabEntity(title))
        }
        tab_layout.setTabData(mTabEntities)
        tab_layout.currentTab = 0
        tab_layout.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                when (position) {
                    0 -> {
                        if (mAllCallAdapter.data.isEmpty()) {
                            loadRecordData()
                        }
                        all_call_recyclerView.visibility = View.VISIBLE
                        wait_call_recyclerView.visibility = View.INVISIBLE
                    }
                    1 -> {
                        if (mWaitCallAdapter.data.isEmpty()) {
                            loadRecordData()
                        }
                        wait_call_recyclerView.visibility = View.VISIBLE
                        all_call_recyclerView.visibility = View.INVISIBLE
                    }
                }
            }

            override fun onTabReselect(position: Int) {
            }

        })
    }

    override fun obtainPresenter() = DZPresent(ArtUtils.obtainAppComponentFromContext(mContext), RxPermissions(this))

    override fun setData(data: Any?) {
    }

    override fun showLoading() {
    }

    override fun handleMessage(message: Message) {
    }

    override fun hideLoading() {
    }

    override fun showMessage(message: String) {
        ArtUtils.snackbarText(message)
    }
}

/**
 * 作者：fanda
 * 描述：全部通话
 */
class AllCallAdapter(val hidenNum :Boolean) : BaseQuickAdapter<CacheAllPhoneRecord, BaseViewHolder>(R.layout.item_call) {

    init {
        addChildClickViewIds(R.id.iv_phone_tips)
    }

    override fun convert(holder: BaseViewHolder, item: CacheAllPhoneRecord) {
        val userName = holder.getView<TextView>(R.id.tv_user_name)
        userName.typeface = Typeface.defaultFromStyle(Typeface.BOLD)//加粗
        var title = if (item.userName.isEmpty()) {
            if (!hidenNum) {
                getFormatPhoneNum(item.customerPhone)
            } else {
                getEncryptPhoneNum(item.customerPhone)
            }
        } else {
            item.userName
        }

        if (item.size > 1) {
            title += "(${item.size})"
        }
        userName.text = title

        if (item.relegation.contains("省")) {
            holder.setText(R.id.tv_user_address, item.relegation.replace("省", "省 "))
        } else {
            holder.setText(R.id.tv_user_address, item.relegation)
        }
        holder.setText(R.id.tv_phone_date, getPhoneDate(item.phoneStartTime))


        if (item.isConnect()) {
            userName.setTextColor(ArtUtils.getColor(context, R.color._333333))
            if (item.isInCall()) {
                holder.setImageResource(R.id.iv_phone_call, R.mipmap.icon_phone_in)
            } else {
                holder.setImageResource(R.id.iv_phone_call, R.mipmap.icon_phone_out)
            }
        } else {
            if (item.isInCall()) {// 接入
                userName.setTextColor(ArtUtils.getColor(context, R.color._F05151))
            } else {
                userName.setTextColor(ArtUtils.getColor(context, R.color._333333))
            }
            holder.setImageResource(R.id.iv_phone_call, R.mipmap.icon_phone_wait)
        }
    }
}

/**
 * 作者：fanda
 * 描述：未接电话
 */
class WaitCallAdapter(val hidenNum :Boolean) : BaseQuickAdapter<CacheWaitPhoneRecord, BaseViewHolder>(R.layout.item_call) {

    init {
        addChildClickViewIds(R.id.iv_phone_tips)
    }

    override fun convert(holder: BaseViewHolder, item: CacheWaitPhoneRecord) {
        val userName = holder.getView<TextView>(R.id.tv_user_name)
        userName.typeface = Typeface.defaultFromStyle(Typeface.BOLD)//加粗
        userName.setTextColor(ArtUtils.getColor(context, R.color._F05151))
        var title = if (item.userName.isEmpty()) {
            if (!hidenNum) {
                getFormatPhoneNum(item.customerPhone)
            } else {
                getEncryptPhoneNum(item.customerPhone)
            }
        } else {
            item.userName
        }

        if (item.size > 1) {
            title += "(${item.size})"
        }
        userName.text = title
        if (item.relegation.contains("省")) {
            holder.setText(R.id.tv_user_address, item.relegation.replace("省", "省 "))
        } else {
            holder.setText(R.id.tv_user_address, item.relegation)
        }
        holder.setText(R.id.tv_phone_date, getPhoneDate(item.phoneStartTime))
        holder.setImageResource(R.id.iv_phone_call, R.mipmap.icon_phone_wait)
    }
}